<template>
    <div class="posts-list-container">
        <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
            <template #rightExtra v-if="activeKey === 'fishSite'">
                <a-button @click="addFishSite">
                    添加钓场
                </a-button>
            </template>
            <a-tab-pane key="posts">
                <template #tab>
                    <span>
                        <icon class="anticon">
                            <template #component>
                                <svg width="1em" height="1em" fill="currentColor" t="1734583509299" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="1504" >
                                    <path
                                        d="M708.9 393.2H329.1c-19.9 0-36.1 16.3-36.1 36.1 0 19.9 16.3 36.1 36.1 36.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0.1-19.8-16.2-36.1-36-36.1zM323.1 627.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0-19.9-16.3-36.1-36.1-36.1H323.1c-19.9 0-36.1 16.3-36.1 36.1s16.3 36.1 36.1 36.1zM702.9 716.4H323.1c-19.9 0-36.1 16.3-36.1 36.1 0 19.9 16.3 36.1 36.1 36.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0.1-19.8-16.2-36.1-36-36.1z"
                                        p-id="1505" ></path>
                                    <path
                                        d="M789.7 64.2H426.8v0.5c-11.8-1.8-23.8 1.7-32.9 10L173.4 277.3c-9.6 8.8-13.8 21.4-11.9 33.7h-0.5v572.6c0 42 33.8 76.2 75.3 76.2h553.4c41.5 0 75.3-34.2 75.3-76.2V140.4c0-42-33.8-76.2-75.3-76.2zM194.8 307.3c-0.6-1.4-1.1-4 1.4-6.3L416.8 98.3c1.3-1.2 2.7-1.6 3.9-1.6 1 0 1.9 0.3 2.5 0.5 1.3 0.6 3.6 2 3.6 5.3V305c0 3.2-2.7 5.9-6 5.9H200.3c-3.5 0.1-4.9-2.2-5.5-3.6z m627 576.3c0 17.9-14.4 32.5-32.1 32.5H236.3c-17.7 0-32.1-14.6-32.1-32.5V362.3c0-10.4 8.4-18.8 18.8-18.8h197.8c21.7 0 39.4-17.2 39.4-38.4V126.7c0-10.4 8.4-18.8 18.8-18.8h310.7c17.7 0 32.1 14.6 32.1 32.5v743.2z"
                                        p-id="1506" ></path>
                                </svg>
                            </template>
                        </icon>
                        我的帖子
                    </span>
                </template>
                <posts-list ref="postsListRef" />
            </a-tab-pane>

            <a-tab-pane key="interflow">
                <template #tab>
                    <span>
                        <icon class="anticon">
                            <template #component>
                                <svg width="1em" height="1em" fill="currentColor" t="1734583509299" class="icon"
                                    viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                                    p-id="2504">
                                    <path
                                        d="M896 128H128c-35.2 0-64 28.8-64 64v640c0 35.2 28.8 64 64 64h768c35.2 0 64-28.8 64-64V192c0-35.2-28.8-64-64-64z m0 640c0 35.2-28.8 64-64 64H192c-35.2 0-64-28.8-64-64V256c0-35.2 28.8-64 64-64h640c35.2 0 64 28.8 64 64v512z"
                                        p-id="2505"></path>
                                    <path d="M256 384h512v64H256zM256 512h512v64H256z" p-id="2506"></path>
                                </svg>
                            </template>
                        </icon>
                        交流帖
                    </span>
                </template>
                <interflow-list ref="interflowListRef" />
            </a-tab-pane>

            <a-tab-pane key="fishSite">
                <template #tab>
                    <span>
                        <icon class="anticon">
                            <template #component>
                                <svg width="1em" height="1em" fill="currentColor" t="1734583742504" class="icon"
                                    viewBox="0 0 1204 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                                    p-id="3176">
                                    <path
                                        d="M544.18184696 90.12549604H325.55146045a41.74078464 41.74078464 0 0 0-40.59924033 31.61579039l-193.56606271 751.23485266a41.74078464 41.74078464 0 0 0 40.69850538 51.86577805h411.94828701a41.84004886 41.84004886 0 0 0 41.9393139-41.79041674V131.91591278A41.69115171 41.69115171 0 0 0 544.18184696 90.12549604z m167.65798974 333.92627462l251.1395582-0.14889715a41.74078464 41.74078464 0 0 0 41.34372528-47.89519273L966.99961316 125.81113681a41.84004886 41.84004886 0 0 0-41.49262326-35.53674363h-213.6671532a41.84004886 41.84004886 0 0 0-41.8896818 41.74078465v250.34544031c0 22.93013398 18.71138645 41.69115171 41.8896818 41.69115252z m370.45566458 452.89495376l-52.95768942-333.77737664a41.84004886 41.84004886 0 0 0-41.54225537-35.58637656h-276.10461694a41.84004886 41.84004886 0 0 0-41.88968098 41.79041675v333.77737747c0 23.0790303 18.71138645 41.79041675 41.88968098 41.79041593h329.06230636a41.93931391 41.93931391 0 0 0 41.54225537-47.99445695z"
                                        p-id="3177"></path>
                                </svg>
                            </template>
                        </icon>
                        我的钓场
                    </span>
                </template>

                <div class="table-container">
                    <a-skeleton active :loading="loading">
                        <template #default>
                            <a-table :columns="fishSiteColumns" :data-source="userFishSiteList" :pagination="pagination"
                                bordered @change="handleTableChange">
                                <template #bodyCell="{ column, record }">
                                    <template v-if="column.key === 'name'">
                                        <router-link :to="{
                                            path: `/angling/detail/${record.fishSiteId}`,
                                        }">
                                            {{ record.name }}
                                        </router-link>
                                    </template>
                                    <template v-if="column.key === 'address'">
                                        {{ record.province + record.city + record.address }}
                                    </template>
                                    <template v-if="column.key === 'publicFlag'">
                                        <a-tag :color="record.publicFlag === 'Y' ? 'processing' : 'default'">
                                            {{ record.publicFlag === 'Y' ? '公开' : '私有' }}
                                        </a-tag>
                                    </template>
                                    <template v-if="column.key === 'feeType'">
                                        <a-tag :color="record.feeType === 'Y' ? 'processing' : 'default'">
                                            {{ record.feeType === 'Y' ? '收费' : '免费' }}
                                        </a-tag>
                                    </template>

                                    <template v-if="column.key === 'action'">
                                        <a-space>
                                            <a-button type="link" @click="editFishSite(record)">
                                                编辑
                                            </a-button>
                                            <a-button type=link @click="toggleVisibility(record)">
                                                {{ record.publicFlag === 'Y' ? '设为私有' : '设为公开' }}
                                            </a-button>
                                            <a-button type="link" danger @click="deleteFishSite(record)">
                                                删除
                                            </a-button>
                                        </a-space>
                                    </template>
                                </template>
                            </a-table>
                        </template>

                    </a-skeleton>
                </div>
            </a-tab-pane>
        </a-tabs>
    </div>
    <!-- 添加/编辑钓场的模态框 -->
    <a-modal v-model:open="modalVisible" :title="modalTitle" @cancel="handleModalCancel" :confirmLoading="modalLoading"
        width="100%" wrap-class-name="full-modal" :footer="null">
        <div class="modal-layout">
            <div class="form-section">
                <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 18 }" @change="handleFormChange">
                    <a-form-item label="名称" name="name">
                        <a-input v-model:value="formState.name" placeholder="请输入钓场名称" style="width: 100%" />
                    </a-form-item>

                    <a-form-item label="所在地区" required class="location-select-item">
                        <div class="location-wrapper">
                            <a-input-group compact style="width: 100%">
                                <a-input style="width: 50%" v-model:value="formState.province" placeholder="省份" disabled
                                    addon-before="省份" />
                                <a-input style="width: 50%" v-model:value="formState.city" placeholder="城市" disabled
                                    addon-before="城市" />
                            </a-input-group>
                            <a-button type="link" @click="useCurrentLocation" class="location-btn">
                                <template #icon><environment-outlined /></template>
                                使用当前位置
                            </a-button>
                        </div>
                        <template #extra>
                            <div class="coordinate-tip">
                                <info-circle-outlined style="color: #1890ff; margin-right: 4px;" />
                                地区信息将通过地图定位自动获取
                            </div>
                        </template>
                    </a-form-item>

                    <a-form-item label="详细地址" name="address">
                        <a-input v-model:value="formState.address" placeholder="请输入详细地址" style="width: 100%" />
                    </a-form-item>

                    <a-form-item label="经纬度">
                        <a-input-group compact>
                            <a-input style="width: 50%" v-model:value="formState.longitude" placeholder="经度" disabled
                                addon-before="经度" />
                            <a-input style="width: 50%" v-model:value="formState.latitude" placeholder="纬度" disabled
                                addon-before="纬度" />
                        </a-input-group>
                        <template #extra>
                            <div class="coordinate-tip">
                                <info-circle-outlined style="color: #1890ff; margin-right: 4px;" />
                                经纬度信息将通过地图定位自动获取
                            </div>
                        </template>
                    </a-form-item>

                    <a-form-item label="收费类型" name="feeType">
                        <a-radio-group v-model:value="formState.feeType">
                            <a-radio value="Y">收费</a-radio>
                            <a-radio value="N">免费</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-form-item label="收费金额" name="amount" v-if="formState.feeType === 'Y'">
                        <a-input-number v-model:value="formState.amount" placeholder="请输入收费金额" :min="0"
                            :precision="2" />
                    </a-form-item>

                    <a-form-item label="可见性" name="publicFlag">
                        <a-radio-group v-model:value="formState.publicFlag">
                            <a-radio value="Y">公开</a-radio>
                            <a-radio value="N">私有</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-form-item label="描述" name="description">
                        <a-textarea v-model:value="formState.description" placeholder="请输入钓场描述" :rows="4" style="width: 100%" />
                    </a-form-item>

                    <a-form-item label="钓场图片" name="imageUrl" required :help="fileList.length === 0 ? '请至少上传一张图片' : ''"
                        :validate-status="fileList.length === 0 ? 'warning' : ''">
                        <div class="upload-wrapper">
                            <a-upload v-model:file-list="fileList" list-type="picture-card"
                                :before-upload="beforeUpload" @preview="handlePreview" @remove="handleRemove"
                                accept="image/*" :customRequest="uploadImage" :maxCount="5">
                                <div v-if="fileList.length < 5">
                                    <plus-outlined />
                                    <div style="margin-top: 8px">上传</div>
                                </div>
                            </a-upload>
                            <a-modal :open="previewOpen" :title="previewTitle" :footer="null"
                                @cancel="handlePreviewCancel">
                                <img alt="preview" style="width: 100%" :src="previewImage" />
                            </a-modal>
                            <div class="upload-tip">
                                <warning-outlined class="warning" />
                                支持 jpg、png 格式，单张大小不超过 2M，最多上传 5 张
                            </div>
                        </div>
                    </a-form-item>
                </a-form>
                <div class="form-footer">
                    <a-space size="middle">
                        <a-button @click="handleModalCancel">取消</a-button>
                        <a-button type="primary" :loading="modalLoading" :disabled="!formValid" @click="handleModalOk">
                            确定
                        </a-button>
                    </a-space>
                </div>
            </div>

            <div class="map-section">
                <div class="map-container" :loading="mapLoading">
                    <div id="map-box" class="map-box">
                        <!-- <GdMap /> -->
                    </div>
                </div>
                <div class="location-actions">
                    <div class="current-location">
                        <div class="location-title">当前定位</div>
                        <div class="location-value">{{ formState.address || '未获取定位' }}</div>
                    </div>
                    <a-button type="primary" :loading="mapLoading" block @click="useCurrentLocation">
                        开始定位
                    </a-button>
                </div>
            </div>
        </div>
    </a-modal>

</template>

<script setup lang="ts">
import "@/styles/userData.scss"
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { anglingSave, anglingSetPublic, anglingUpdate, anglingUserList } from '@/api/front/angling';
import { AnglingVO } from '@/api/front/angling/types';
import Icon from '@ant-design/icons-vue';
import { debounce } from 'lodash-es';
import { EnvironmentOutlined, InfoCircleOutlined, PlusOutlined, WarningOutlined } from '@ant-design/icons-vue';
import { uploadImageApi } from '@/api/common';
import AMapLoader from "@amap/amap-jsapi-loader";
import { GD_MAP_API_KEY, GD_MAP_SECRET } from "@/utils/gdMap";
import PostsList from './PostsList.vue';
import InterflowList from './InterflowList.vue';

// 首先声明所有的 ref
const router = useRouter();
const loading = ref(false);
const activeKey = ref('posts');
const postsListRef = ref<InstanceType<typeof PostsList>>();
const interflowListRef = ref<InstanceType<typeof InterflowList>>();
const userFishSiteList = ref<AnglingVO[]>([]);

// 修改 refreshCurrentTab 函数
const refreshCurrentTab = async () => {
    console.log('refreshCurrentTab', activeKey.value);
    // 添加延时确保组件已经挂载
    await nextTick();
    switch (activeKey.value) {
        case 'posts':
            postsListRef.value?.getList();
            break;
        case 'interflow':
            interflowListRef.value?.getList();
            break;
        case 'fishSite':
            getList('fishSite');
            break;
    }
};

// 修改 handleTabChange 函数
const handleTabChange = async (key: string) => {
    activeKey.value = key;
    await refreshCurrentTab();
};

// 钓场列表的配置
const fishSiteColumns = [
    {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '可见状态',
        dataIndex: 'publicFlag',
        key: 'publicFlag',
        width: '10%',
    },
    {
        title: '收费类型',
        dataIndex: 'feeType',
        key: 'feeType',
        width: '10%',
    },
    {
        title: '操作',
        key: 'action',
        width: '30%',
    }
];

const pagination = {
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: false,
    showTotal: (total: number) => `共 ${total} 条`
};

const handleTableChange = (pag: any, filters: any, sorter: any) => {
    pagination.current = pag.current;
    getList(activeKey.value)
};

// 获取列表数据
const getList = async (type: string) => {
    loading.value = true;
    try {
        if (type === 'fishSite') {
            const res = await anglingUserList({
                pageNum: pagination.current,
                pageSize: pagination.pageSize,
                orderByColumn: 'create_time',
                isAsc: 'desc'
            });
            userFishSiteList.value = res.data.rows;
            pagination.total = res.data.total;
        }
    } catch (error) {
        message.error('获取数据失败');
    } finally {
        setTimeout(() => {
            loading.value = false;
        }, 300);
    }
};

// 模态框相关状态
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalTitle = ref('');
const formRef = ref();

// 表单数据
const formState = reactive({
    fishSiteId: '',
    name: '',
    province: '',
    city: '',
    address: '',
    feeType: 'N',
    amount: undefined,
    publicFlag: 'Y',
    description: '',
    longitude: '',
    latitude: '',
    images: [],
    imageUrl: '',
});

// 表单验证规则
const rules = {
    name: [{ required: true, message: '请输入钓场名称', trigger: 'blur' }],
    address: [{ required: true, message: '请输入钓场地址', trigger: 'blur' }],
    feeType: [{ required: true, message: '请选择收费类型', trigger: 'change' }],
    amount: [{ required: true, message: '请输入收费金额', trigger: 'blur' }],
    publicFlag: [{ required: true, message: '请选择可见性', trigger: 'change' }],
    imageUrl: [{
        required: true,
        message: '请至少上传一张图片',
        validator: (rule: any, value: string) => {
            if (!value || value.split(',').filter(Boolean).length === 0) {
                return Promise.reject('请至少上传一张图片');
            }
            return Promise.resolve();
        }
    }],
};

// 图片上传相关状态
const fileList = ref<any[]>([]);
const previewOpen = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

// 图片预览
const handlePreview = async (file: any) => {
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewOpen.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 关闭预览
const handlePreviewCancel = () => {
    previewOpen.value = false;
};

// 删除图片
const handleRemove = (file: any) => {
    const urls = formState.imageUrl.split(',').filter(Boolean);
    const index = urls.indexOf(file.url);
    if (index > -1) {
        urls.splice(index, 1);
        formState.imageUrl = urls.join(',');
    }
    validateForm();  // 删除图片后验证表单
};

// 上传前验证
const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
        return false;
    }
    return true;
};

// 自定义上传图片
const uploadImage = async (options: any) => {
    const { file, onSuccess, onError } = options;
    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await uploadImageApi(formData);
        const { url, fileName, ossId } = response.data;

        // 更新图片URL列表
        const urls = formState.imageUrl.split(',').filter(Boolean);
        urls.push(url);
        formState.imageUrl = urls.join(',');

        // 更新文件列表
        fileList.value.push({
            uid: ossId,
            name: fileName,
            status: 'done',
            url
        });

        onSuccess(response.data, file);
        message.success('上传成功');
        validateForm();  // 上传成功后验证表单
    } catch (error) {
        onError(error);
        message.error('上传失败');
    }
};

// 将文件转换为 Base64
const getBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });
};

// 打开新增钓场模态框
const addFishSite = () => {
    modalTitle.value = '新增钓场';
    formValid.value = false;  // 重置表单验证状态
    // 重置表单数据
    Object.assign(formState, {
        fishSiteId: '',
        name: '',
        address: '',
        feeType: 'N',
        amount: undefined,
        province: '',
        city: '',
        publicFlag: 'Y',
        description: '',
        longitude: '',
        latitude: '',
        imageUrl: '',  // 确保清空图片URL
    });
    fileList.value = [];  // 清空文件列表

    modalVisible.value = true;
    nextTick(() => {
        initMap();
    });
};

// 打开编辑钓场模态框
const editFishSite = (record: AnglingVO) => {
    modalTitle.value = '编辑钓场';
    formValid.value = false;  // 重置表单验证状态
    // 填充表单数据
    Object.assign(formState, {
        fishSiteId: record.fishSiteId,
        name: record.name,
        province: record.province,
        city: record.city,
        address: record.address,
        feeType: record.feeType,
        amount: record.amount,
        publicFlag: record.publicFlag,
        description: record.description,
        longitude: record.longitude,
        latitude: record.latitude,
        imageUrl: record.imageUrl || '',
    });
    // 设置文件列表
    fileList.value = (record.imageUrl || '').split(',')
        .filter(Boolean)  // 过滤空字符串
        .map((url: string, index: number) => ({
            uid: `-${index}`,
            name: url.substring(url.lastIndexOf('/') + 1),
            status: 'done',
            url,
        }));
    nextTick(() => {
        initMap();
        validateForm();  // 编辑时立即验证表单
    });
    modalVisible.value = true;
};

// 处理模态框确认
const handleModalOk = async () => {
    try {
        modalLoading.value = true;
        // 表单验证
        await formRef.value.validate();

        // 根据是否有 fishSiteId 判断是新增还是编辑
        if (formState.fishSiteId) {
            // 调用编辑接口
            await anglingUpdate(formState);
            message.success('编辑成功');
        } else {
            // 调用新增接口
            await anglingSave(formState);
            message.success('添加成功');
        }

        modalVisible.value = false;
        // 刷新列表
        await getList(activeKey.value);
    } catch (error) {
        if (error instanceof Error) {
            // 表单验证错误
            return;
        }
        message.error('操作失败');
    } finally {
        modalLoading.value = false;
    }
};

let map = null;
let geolocation = null;

const initMap = () => {
    window._AMapSecurityConfig = {
        securityJsCode: GD_MAP_SECRET,
    };
    AMapLoader.load({
        key: GD_MAP_API_KEY,
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.Geolocation"],
    })
        .then((AMap) => {
            // 默认中心点
            let center = [108.23847, 22.831271];
            let zoom = 11;  // 默认缩放级别

            // 如果表单中存在经纬度，则使用表单中的经纬度作为中心点
            if (formState.longitude && formState.latitude) {
                center = [Number(formState.longitude), Number(formState.latitude)];
                zoom = 15;  // 编辑模式下使用更大的缩放级别
            }

            map = new AMap.Map("map-box", {
                viewMode: "3D",
                zoom: zoom,
                center: center,
                resizeEnable: true,
            });

            // 如果存在经纬度，添加标记点
            if (formState.longitude && formState.latitude) {
                const marker = new AMap.Marker({
                    position: center,
                    animation: 'AMAP_ANIMATION_DROP'  // 点标记的动画效果
                });
                map.add(marker);
            }

            // Ip定位
            AMap.plugin('AMap.Geolocation', () => {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,
                    timeout: 10000,
                    offset: [10, 20],
                    zoomToAccuracy: true,
                    position: 'RB',
                    showButton: false,
                    convert: true,
                    needAddress: true
                });
                map.addControl(geolocation);
            });
        })
        .catch((e) => {
            console.error('地图加载失败:', e);
            message.error('地图加载失败');
        });
};

const mapLoading = ref(false);
// 修改使用当前位置的方法
const useCurrentLocation = async () => {
    mapLoading.value = true;
    try {
        await geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
                formState.longitude = result.position.lng;
                formState.latitude = result.position.lat;
                formState.province = result.addressComponent.province;
                formState.city = result.addressComponent.city;
                formState.address = result.formattedAddress;

                // 清除现有标记点
                map.clearMap();

                // 添加新的标记点
                const marker = new AMap.Marker({
                    position: [result.position.lng, result.position.lat],
                    animation: 'AMAP_ANIMATION_DROP'
                });
                map.add(marker);

                // 将地图中心移动到定位点
                map.setZoomAndCenter(15, [result.position.lng, result.position.lat]);
                validateForm();  // 位置更新后验证表单
            } else {
                message.error('定位失败');
            }
            mapLoading.value = false;
        });
    } catch (error) {
        console.error('定位错误:', error);
        message.error('定位失败');
        mapLoading.value = false;
    }
};


// 处理模态框消
const handleModalCancel = () => {
    modalVisible.value = false;
    formRef.value?.resetFields();
    fileList.value = [];
    formState.imageUrl = '';
    formValid.value = false;  // 重置表单验证状态
};

// 删除钓场
const deleteFishSite = async (record: AnglingVO) => {
    try {
        // TODO: 实现删除钓场功能
        message.success('删除成功');
        await getList(activeKey.value);
    } catch (error) {
        message.error('删除失败');
    }
};

// 跳转到编辑页面
const goToEdit = (record: any) => {
    router.push({
        path: '/user/postEdit',
        query: { postId: record.postId }
    });
};

// 切换钓场可见性
const toggleVisibility = debounce(async (record: AnglingVO) => {
    try {
        loading.value = true;
        await anglingSetPublic({
            fishSiteId: record.fishSiteId,
            publicFlag: record.publicFlag === 'Y' ? 'N' : 'Y'
        });
        message.success('设置成功');
        // 重新加载列表
        await getList(activeKey.value);
    } catch (error) {
        message.error('设置失败');
    } finally {
        loading.value = false;
    }
}, 500);

onMounted(async () => {
    await refreshCurrentTab();
});

// 修改 switchTab 函数
const switchTab = async (type: string) => {
    activeKey.value = type;
    await refreshCurrentTab();
};

// 添加一个表单验证状态变量
const formValid = ref(false);

// 添加表单验证状态监听函数
const validateForm = async () => {
    try {
        await formRef.value.validate();
        formValid.value = true;
    } catch (error) {
        formValid.value = false;
    }
};

// 修改表单的值时触发验证
const handleFormChange = () => {
    validateForm();
};

defineExpose({
    switchTab
});
</script>

<style lang="scss" scoped>
.posts-list-container {
    padding: 24px;
}
</style>
